package com.fee.xmediaplayer.demo

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.SurfaceHolder
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.fee.xmediaplayer.demo.databinding.ActivityPlayerBinding
import tv.danmaku.ijk.media.player.IMediaPlayer

/**
 * 播放界面
 */
class PlayerActivity : AppCompatActivity(),IPlayerListener, View.OnClickListener,
    SurfaceHolder.Callback {

    private lateinit var mViewBinding: ActivityPlayerBinding

    private var mTestAVideoPath: String = ""
    private var mTestBVideoPath = ""
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewBinding = ActivityPlayerBinding.inflate(layoutInflater)
        setContentView(mViewBinding.root)
        mViewBinding.btnNext.setOnClickListener(this)
        mViewBinding.btnPause.setOnClickListener(this)
        mViewBinding.btnPlay.setOnClickListener(this)
        mViewBinding.btnPlayEmpty.setOnClickListener(this)
        mViewBinding.btnRelease.setOnClickListener(this)
        mViewBinding.btnStop.setOnClickListener(this)

        SingleMediaPlayer.player.addPlayerListener(this)
        Log.i("info","--> onCreate() holde = ${mViewBinding.surfaceView.holder}")
        mViewBinding.surfaceView.holder.addCallback(this)
        checkAndRequestPermissions()
    }

    private fun checkAndRequestPermissions() {
        if (Build.VERSION.SDK_INT < 23) {
            return
        }
        val necessaryPermission = Manifest.permission.WRITE_EXTERNAL_STORAGE
        val permissionState = ContextCompat.checkSelfPermission(this,necessaryPermission)
        if (PackageManager.PERMISSION_GRANTED != permissionState) {
            requestPermissions(arrayOf(necessaryPermission),100)
        } else{
            getVideoPath()
        }
    }
    /**
     * 播放器 播放完成的回调
     * @param player 当前播放器
     */
    override fun onCompletion(player: IMediaPlayer) {
        toast("播放完成")
    }

    /**
     * 播放器 错误信息的 回调
     * @param player 当前播放器
     * @param what 错误类型
     * @param extra 额外信息
     * @return true: 是啥意思？；false:
     */
    override fun onError(player: IMediaPlayer, what: Int, extra: Int): Boolean {
        toast("onError(): what = $what, extra = $extra")
        return false
    }

    private fun toast(toastMsg: String?) {
        Toast.makeText(this,toastMsg,Toast.LENGTH_LONG).show()
    }

    private fun getVideoPath() {
        val rootPath = Environment.getExternalStorageDirectory().absolutePath + "/"
        if (mTestAVideoPath.isBlank()) {
            mTestAVideoPath = "${rootPath}a.mp4"
        }

        if (mTestBVideoPath.isBlank()) {
            mTestBVideoPath = "${rootPath}b.mp4"
        }

    }
    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    override fun onClick(v: View?) {
        getVideoPath()
        when (v?.id) {
            R.id.btnNext -> {
                SingleMediaPlayer.player.play(mTestBVideoPath)
            }
            R.id.btnPlay ->{
                SingleMediaPlayer.player.start()
            }
            R.id.btnPause ->{//暂停
                SingleMediaPlayer.player.pause()
            }
            R.id.btnStop -> {//停止
                SingleMediaPlayer.player.stop()
            }
            R.id.btnPlayEmpty ->{
                SingleMediaPlayer.player.play(SingleMediaPlayer.PATH_OF_EMPTY_MEDIA)
                //
            }
            R.id.btnRelease ->{
                SingleMediaPlayer.player.release()
            }
            else -> {}
        }
    }

    /**
     * This is called immediately after the surface is first created.
     * Implementations of this should start up whatever rendering code
     * they desire.  Note that only one thread can ever draw into
     * a [Surface], so you should not draw into the Surface here
     * if your normal rendering will be in another thread.
     *
     * @param holder The SurfaceHolder whose surface is being created.
     */
    override fun surfaceCreated(holder: SurfaceHolder) {
        Log.i("info", "--> surfaceCreated() holder = $holder")
        SingleMediaPlayer.player.setDisplay(holder)
    }

    /**
     * This is called immediately after any structural changes (format or
     * size) have been made to the surface.  You should at this point update
     * the imagery in the surface.  This method is always called at least
     * once, after [.surfaceCreated].
     *
     * @param holder The SurfaceHolder whose surface has changed.
     * @param format The new [PixelFormat] of the surface.
     * @param width The new width of the surface.
     * @param height The new height of the surface.
     */
    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
        Log.i(
            "info", "--> surfaceChanged() holder = $holder, format = $format, width = $width," +
                    " height = $height"
        )

    }

    /**
     * This is called immediately before a surface is being destroyed. After
     * returning from this call, you should no longer try to access this
     * surface.  If you have a rendering thread that directly accesses
     * the surface, you must ensure that thread is no longer touching the
     * Surface before returning from this function.
     *
     * @param holder The SurfaceHolder whose surface is being destroyed.
     */
    override fun surfaceDestroyed(holder: SurfaceHolder) {
        Log.i("info", "--> surfaceDestroyed() holder = $holder")
    }

}